<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Wechat\CreateRequest;
use App\Models\Wechat;
use App\Http\Controllers\Controller;

class WecahtController extends Controller
{

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $user = \Auth::user();
        if (!$user->hasPermissionTo('微信配置')) {
            return view('error.error');
        }
        $wechat = Wechat::first();
        return view('wechat.create')->with(['wechat' => $wechat]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param CreateRequest $request
     * @return \Illuminate\Http\Response
     * @throws \Throwable
     */
    public function store(CreateRequest $request)
    {
        $model = \DB::transaction(function () use ($request) {
            $attributes = $this->upload($request);
            $wechat = Wechat::first();
            $model = is_null($wechat) ? Wechat::create($attributes) : $wechat->update($attributes);
            return $model;
        });
        return redirect()->route('wechat.create')->with('success', '添加成功');
    }

    protected function upload(CreateRequest $request)
    {
        $attributes = $request->validated();
        $plucks = array_keys($attributes);
        foreach ($plucks as $key => $value) {
            if (!$request->hasFile($value)) {
                !is_null($request->input($value)) && $attributes[$value] = $request->input($value);
                continue;
            }
            $file_f = $request->file($value);
            $attributes[$value] = \Storage::putFile('private/cert', $file_f);
        }
        return $attributes;
    }
}
